//
//  rootViewController.m
//  百车易车险
//
//  Created by chenxu on 15/3/7.
//  Copyright (c) 2015年 chenxu. All rights reserved.
//

#import "rootViewController.h"
#import "DriverViewController.h"
#import "OrderlistViewController.h"
#import "NetAPIManager.h"
#import "BConnector.h"
#import "NetBaiduManager.h"
#import "Insurances.h"
#import "Helper.h"
#import "AlipayHeader.h"

@interface rootViewController ()

@end

@implementation rootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
  
    [self.view bringSubviewToFront:_view1];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = kColorTheme;

    _myTableview.tableFooterView = [self tableFooterView];
    [_oldnew setPopingPressed];
    [_oldold setPopingPressed];
    [_newnew setPopingPressed];
    [_newold setPopingPressed];
    [_girl setPopingPressed];
    
    UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarTapped)];
    tapped.numberOfTapsRequired = 1;
    [_avatar addGestureRecognizer:tapped];
    //圆形裁剪
    _avatar.layer.masksToBounds = YES;
    _avatar.layer.cornerRadius = 40;//保证是图片宽度一半
   
    [[NetAPIManager sharedManager]loadImageWithPath:[[Login curLoginUser]getIconUrl] completeBlock:^(UIImage *image, NSError *error) {
        if (image) {
            _avatar.image = image;
        }
    }];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receivemsg:) name:@"newmsg" object:nil];



    
}

- (void)receivemsg:(NSNotification*)notify{
    //[self performSegueWithIdentifier:@"orderlist" sender:[NSNumber numberWithBool:true]];
}

/*!
 *  @brief  点击头像的回调
 */
- (void)avatarTapped{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"更换头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
    [actionSheet showInView:kKeyWindow];
}


#pragma mark UIActionSheetDelegate M
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 2) {
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;//设置可编辑
    
    if (buttonIndex == 0) {
        //        拍照
        if (![Helper checkCameraAuthorizationStatus]) {
            return;
        }
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }else if (buttonIndex == 1){
        //        相册
        if (![Helper checkPhotoLibraryAuthorizationStatus]) {
            return;
        }
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    
}
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //    NSLog(@"%@", info);
    UIImage *editedImage, *originalImage;
    editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [[NetAPIManager sharedManager]request_UpdateUserIconImage:editedImage withParam:[[Login curLoginUser] toUsernameParams] successBlock:^(id responseObj) {
        _avatar.image = responseObj;
    } failureBlock:^(NSError *error) {
        
    } progerssBlock:^(CGFloat progressValue) {
        
    }];
    
    // 保存原图片到相册中
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        SEL selectorToCall = @selector(imageWasSavedSuccessfully:didFinishSavingWithError:contextInfo:);
        UIImageWriteToSavedPhotosAlbum(originalImage, self,selectorToCall, NULL);
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}


// 保存图片后到相册后，调用的相关方法，查看是否保存成功
- (void) imageWasSavedSuccessfully:(UIImage *)paramImage didFinishSavingWithError:(NSError *)paramError contextInfo:(void *)paramContextInfo{
    if (paramError == nil){
        NSLog(@"Image was saved successfully.");
    } else {
        NSLog(@"An error happened while saving the image.");
        NSLog(@"Error = %@", paramError);
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

/*!
 *  @brief  更新用户信息
 *  @param animated 是否有动画
 */
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self refresh];
}


- (UIView*)tableFooterView{
    
    UIView *footerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 90)];
    
    UIButton *saveBtn = [UIButton buttonWithStyle:StrapWarningStyle andTitle:@"退出" andFrame:CGRectMake(30, 25, kScreen_Width-30*2, 35) target:self action:@selector(logout:)];
    [saveBtn setPopingPressed];
    [footerV addSubview:saveBtn];
    return footerV;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)changeview:(id)sender {
    UISegmentedControl *segmentedControl = sender;
    NSInteger index = [segmentedControl selectedSegmentIndex];
    if(index==0){
        [self.view bringSubviewToFront:_view1];
    }
    else if(index==1){
        if([Login isLogin] == false){
            [self performSegueWithIdentifier:@"login" sender:self];
        }
        else{
            [self.view bringSubviewToFront:_view2];
        }
    }
}
- (void)logout:(id)sender {
    [[NetAPIManager sharedManager] request_Logout_WithParams:[self.user tousernameParams] andBlock:^(id data, NSError *error) {
        
        if (data) {
            NSLog(@"成功退出");
            [self performSegueWithIdentifier:@"login" sender:self];

        }else{
            NSLog(@"退出失败");
            //[weakSelf refreshCaptchaNeeded];
        }
    }];
}



#pragma mark - table view
#pragma mark Table Data Source Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section != 2) {
        return 2;
    }
    else
        return 1;
}
#pragma mark Table Delegate Methods
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *CellIdentifier = @"me";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (indexPath.section == 0) {
        if (indexPath.row ==0){
            cell.textLabel.text = @"已完成订单";
            [cell.imageView setImage:[UIImage imageNamed:@"已完成订单"]];
        }
        else{
             cell.textLabel.text = @"未完成订单";
            [cell.imageView setImage:[UIImage imageNamed:@"未完成订单"]];

        }
    }
    else if(indexPath.section == 1)
    {
        if (indexPath.row ==0){
            cell.textLabel.text = @"信息中心";
            [cell.imageView setImage:[UIImage imageNamed:@"信息中心"]];

        }
        else{
            cell.textLabel.text = @"申请客服";
            [cell.imageView setImage:[UIImage imageNamed:@"申请客服"]];

        }
    }
 
    return cell;
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self performSegueWithIdentifier:@"orderlist" sender:[NSNumber numberWithBool:true]];
        }
        else{
            [self performSegueWithIdentifier:@"orderlist" sender:[NSNumber numberWithBool:false]];
        }
    }
    else{
        if (indexPath.row == 0) {
            
        }
        else{
            [self performSegueWithIdentifier:@"feedback" sender:[NSNumber numberWithBool:false]];
        }
    }
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSString* kind = segue.identifier;
    DriverViewController* nextView = [segue destinationViewController];
    if ([kind  isEqual: @"newnew"]) {
        [nextView setDriver:kind];
    }
    if([kind isEqualToString:@"newold"]){
        [nextView setDriver:kind];
    }
    if([kind isEqualToString:@"oldnew"]){
        [nextView setDriver:kind];
    }
    if([kind isEqualToString:@"oldold"]){
        [nextView setDriver:kind];
    }
    if([kind isEqualToString:@"girl"]){
        [nextView setDriver:kind];
    }
    if ([kind isEqualToString:@"orderlist"]){
        OrderlistViewController* orderlistview = [segue destinationViewController];
        orderlistview.finished = [sender boolValue];
        
    }
    
}

/*!
 *  @brief  刷新界面上的元素
 */
- (void)refresh{
    //读取用户
    NSString* name = @"用户名:";
    NSString* phone = @"手机号:";
    if([Login isLogin]) {
        _user = [Login curLoginUser];
        if (_user.Username != nil) {
            _name.text = [name  stringByAppendingString:_user.Username];
        }
        if (_user.Phone != nil) {
            _phone.text = [phone stringByAppendingString:_user.Phone];
        }
    }
    [self getLimitnumber];
}

- (void)getLimitnumber{
    [[NetAPIManager sharedManager] request_limitNumber:nil andBlock:^(id data, NSError *error) {
        if (data) {
            NSString* nums = [data valueForKeyPath:@"Limitnumber"];
            NSString* first = @"  今日限行尾号: ";
            _notice.text = [first stringByAppendingString:nums];
        }else{
            
        }
    }];
}
@end
